import re

from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from rest_framework_simplejwt.tokens import RefreshToken

from .models import LuffyUserModel


class LuffyUserSerializer(serializers.ModelSerializer):
    username = serializers.CharField()

    class Meta:
        model = LuffyUserModel
        fields = ["username", "password", "id"]
        extra_kwargs = {
            "id": {"read_only": True},
            "password": {"write_only": True}
        }

    def validate(self, attrs):
        # 获取用户对象
        user = self._get_user(attrs)

        # 签发token
        refresh = RefreshToken.for_user(user)
        token = str(refresh.access_token)
        refresh = str(refresh)
        # 放入上下文中，以便视图进行获取
        self.context["user"] = user
        self.context["token"] = token
        self.context["refresh"] = refresh

        return attrs

    def _get_user(self, attrs):
        """
        根据用户提交的用户信息，返回用户对象
        """
        # 获取用户提交的用户名和密码
        username = attrs.get("username")
        password = attrs.get("password")

        # 匹配手机号
        if re.match("^1[3-9][0-9]{9}$",
                    username):
            try:
                user = LuffyUserModel.objects.get(mobile=username)
            except Exception:
                user = None
        # 匹配电子邮箱
        elif re.match("[a-zA-Z0-9\.]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]+", username):
            try:
                user = LuffyUserModel.objects.get(email=username)
            except Exception:
                user = None
        # 匹配用户名
        else:
            try:
                user = LuffyUserModel.objects.get(username=username)
            except Exception:
                user = None

        # 验证密码
        if user:
            if user.check_password(password):
                return user
            else:
                raise ValidationError("密码错误！")
        else:
            raise ValidationError("用户不存在！")


class UserRegisterSerializer(serializers.ModelSerializer):

    class Meta:
        model = LuffyUserModel
        fields = ["mobile", "password", "username"]
        extra_kwargs = {
            "password": {"max_length": 18, "min_length": 8},
            "username": {"read_only": True}
        }

    def validate(self, attrs):
        mobile = attrs.get("mobile")
        if re.match("^1[3-9][0-9]{9}$", mobile):
            return attrs
        else:
            raise ValidationError("手机号不合法")

    def create(self, validated_data):
        moblie = validated_data.get("mobile")
        password = validated_data.get("password")
        # 暂时用手机号充当用户名
        user = LuffyUserModel.objects.create_user(username=moblie, password=password, mobile=moblie)
        return user
